package com.example.singleton.hungry;

import java.util.concurrent.CountDownLatch;

/**
 * 饿汉式单利 是 线程安全的
 * <p>
 * 不管系统用不用，只要该类加载就会初始化
 * 类的加载过程如下：加载、连接（验证、准备、解析）、初始化、使用、卸载
 */
public class HungryStaticSingleton {

    private static final HungryStaticSingleton instance;

    static {
        instance = new HungryStaticSingleton();
    }

    private HungryStaticSingleton() { }

    public static HungryStaticSingleton getInstance() {
        return instance;
    }




    public static void main(String[] args) {

        int count = 100;
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                    HungryStaticSingleton.getInstance();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            latch.countDown();
        }
    }
}
